package org.linlinjava.litemall.wx.web;

import org.apache.commons.lang.StringUtils;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.SignRecord;
import org.linlinjava.litemall.wx.annotation.LoginUser;
import org.linlinjava.litemall.wx.service.SignInService;
import org.linlinjava.litemall.wx.util.GetTomorrowSecond;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户签到
 *
 * @author zhy
 * @date 2019-07-02 9:22
 **/
@RestController
@RequestMapping("/wx/sign")
public class WxSignInController {
	@Resource
	private SignInService signInService;

	@Resource
	private GetTomorrowSecond getTomorrowSecond;

	@GetMapping("/signToday")
	public Object signToday(@LoginUser Integer userId) {
		if (userId == null) {
			return ResponseUtil.unlogin();
		}
		// 判断用户今天是否还有抽奖机会
		try (Jedis jedis = new Jedis("localhost", 6379)) {
			long c = jedis.incr(userId + "sign");
			if (c > 1) {
				return ResponseUtil.fail(-1, "今日已签到啦");
			} else {
				long allNum = jedis.incr("signNum");
				if (allNum == 1) {
					//设置过期时间
					jedis.expire("signNum", getTomorrowSecond.getSecond());
				}
				if (c == 1) {
					//设置过期时间
					jedis.expire(userId + "sign", getTomorrowSecond.getSecond());
				}
			}
		}

		//1.查看用户今天签到了没有，没有则可以签到，有则返回已签到
		SignRecord signRecord = signInService.getRecord(userId);
		if (signRecord == null) {
			//2.为用户增加1积分，增加钱包记录，增加签到记录
			return ResponseUtil.ok(signInService.insertRecord(userId));
		} else {
			return ResponseUtil.fail(-1, "今日已签到啦");
		}
	}

	@GetMapping("/monthSign")
	public Object getMonthSign(@LoginUser Integer userId) {
		if (userId == null) {
			return ResponseUtil.unlogin();
		}
		LocalDate today = LocalDate.now();
		LocalDate first = today.with(TemporalAdjusters.firstDayOfMonth());
		LocalDate last = today.with(TemporalAdjusters.lastDayOfMonth());
		String num = "0" ;
		try (Jedis jedis = new Jedis("localhost", 6379)) {
			 String nums = jedis.get("signNum");
			 if(StringUtils.isNotEmpty(nums)){
			 	num = nums;
			 }
		}
		List<SignRecord> list = signInService.getUserRecord(userId, first, last);
		List<Integer> list1 = new ArrayList<>(16);
		for (SignRecord signRecord : list) {
			String date = signRecord.getSignInDate().toString().substring(8, 10);
			if (date.startsWith("0")) {
				date = date.substring(1, 2);
			}
			list1.add(Integer.valueOf(date));
		}
		Map<String, Object> map = new HashMap<>(2);
		map.put("items", list1);
		map.put("num", num);
		return ResponseUtil.ok(map);
	}

}
